package com.lanou.horo.zhuizhui.fragment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.lanou.horo.zhuizhui.activity.CartoonMessageActivity;
import com.lanou.horo.zhuizhui.activity.EveryDayActivity;
import com.lanou.horo.zhuizhui.activity.MustBeChasedActivity;
import com.lanou.horo.zhuizhui.activity.SelectedAlbumActivity;
import com.lanou.horo.zhuizhui.activity.WebViewActivity;
import com.lanou.horo.zhuizhui.adapter.HomeAdapter;
import com.lanou.horo.zhuizhui.entity.SearchIconItem;


import com.lanou.horo.zhuizhui.entity.HomePageItem;


import com.lanou.horo.zhuizhui.entity.PictureNewItem;
import com.lanou.horo.zhuizhui.utility.customDialog.CustomProgressDialog;
import com.lanou.horo.zhuizhui.utility.customDialog.ProgressDialogG;
import com.lanou.horo.zhuizhui.utility.clickInterface.HomePageItemClickListener;
import com.lanou.horo.zhuizhui.R;
import com.lanou.horo.zhuizhui.utility.scroll.TopDecoration;
import com.lanou.horo.zhuizhui.utility.scroll.TopTrackListener;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class HomePageFragment extends Fragment implements HomePageItemClickListener,
        SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView recyclerView;
    private RecyclerViewHeader recyclerViewHeader;
    private RequestQueue queue;
    private HomeAdapter adapter;
    private ImageView toggle;
    private SwipeRefreshLayout swipeRefreshWidget;
    private int lastVisibleItem;
    private CustomProgressDialog dialog;
    private boolean isdialogshowing = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    swipeRefreshWidget.setRefreshing(true);
                    if (adapter.getEntities() != null) {
                        adapter.getEntities().clear();
                        initData();
                    }
                    break;
            }
        }
    };
    ;

    @Override
    @Nullable
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page_home, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.homeRecycler);
        recyclerViewHeader = (RecyclerViewHeader) view.findViewById(R.id.herder);
        recyclerView.addItemDecoration(new TopDecoration(view.findViewById(R.id.main_top_view)));
        recyclerView.addOnScrollListener(new TopTrackListener(view.findViewById(R.id.main_top_view)));
        swipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.homepageSwipeRefresh);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        dialog = new CustomProgressDialog(getActivity(), "加载中...", R.anim.loding);
        dialog.setCanceledOnTouchOutside(false);
//        dialog = (CustomProgressDialog) ProgressDialogG.createProgressDialogG(getActivity(),
// 10, new CustomProgressDialog.OnTimeOutListener() {
//            @Override
//            public void onTimeOut(ProgressDialogG dialog) {
//                Toast.makeText(getActivity(), "网络超时,请检查网络", Toast.LENGTH_SHORT).show();
//            }
//
//        });
//        dialog.createProgressDialogG(getContext(), 10, new ProgressDialogG.OnTimeOutListener() {
//            @Override
//            public void onTimeOut(ProgressDialogG dialog) {
//                Toast.makeText(getActivity(), "网络超时,请检查网络", Toast.LENGTH_SHORT).show();
//            }
//        });
        dialog.createProgressDialogG(getContext(), 5, new ProgressDialogG.OnTimeOutListener() {
            @Override
            public void onTimeOut(ProgressDialogG dialog) {
                Toast.makeText(getActivity(), "网络超时,请检查网络", Toast.LENGTH_SHORT).show();
            }
        });


        GridLayoutManager manager = new GridLayoutManager(getActivity(), 1);
        manager.setOrientation(LinearLayout.VERTICAL);
        swipeRefreshWidget.setColorSchemeColors(0xff00aa00, 0xfffedcba, 0xff123456, 0xff654321);
        swipeRefreshWidget.setOnRefreshListener(this);
        swipeRefreshWidget.setProgressViewOffset(false, 50, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources()
                        .getDisplayMetrics()));
        swipeRefreshWidget.setProgressViewEndTarget(true, 100);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(manager);
        recyclerViewHeader.attachTo(recyclerView, true);
        adapter = new HomeAdapter(getActivity());
        recyclerView.setAdapter(adapter);
        adapter.setItemClickListener(this);
    }


    public void initData() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        queue = Volley.newRequestQueue(getActivity());
        String url = "http://api.zhuizhuiyoyo.com/request.php?" +
                "method=homepage&timestamp=" + "1445236202846" +
                "&param=%7B%22v%22%3A1%7D&sig=9dec81b9eb490eea3d73e9045e6aaabf";
        StringRequest request = new StringRequest(url, new Listener<String>() {
            @Override
            public void onResponse(String response) {

                Gson gson = new Gson();
                HomePageItem hpi = gson.fromJson(response, HomePageItem.class);
                if (hpi != null) {
                    List<HomePageItem.ListsEntity> entities = hpi.getLists();
                    if (entities != null && entities.size() > 0) {
                        adapter.addData(entities);
                    }
                }

                swipeRefreshWidget.setRefreshing(false);
                if (isdialogshowing == true) {
                    dialog.dismiss();
                    isdialogshowing = false;
                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders()
                    throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);
    }

    @Override
    public void homePageItemClick(HomePageItem.ListsEntity hlid) {

        Intent intent = new Intent();
        intent.putExtra("id", hlid.getId());
//        Toast.makeText(getContext(), "id:" + hlid.getId(), Toast.LENGTH_SHORT).show();

        switch (hlid.getId()) {
            case 56:
                intent.setClass(getActivity(), CartoonMessageActivity.class);//今日追追资讯
                startActivity(intent);
                break;
            case 18:
                intent.setClass(getActivity(), CartoonMessageActivity.class); //热门话题
                startActivity(intent);
            case 49:
                intent.setClass(getActivity(), CartoonMessageActivity.class); //往期词典
                startActivity(intent);
                break;
            case 53:
                intent.setClass(getActivity(), CartoonMessageActivity.class); //黑白漫
                startActivity(intent);
                break;
            case 51:
                intent.setClass(getActivity(), CartoonMessageActivity.class); //安利
                startActivity(intent);
                break;
            case 57:
                intent.setClass(getActivity(), EveryDayActivity.class);//每日漫评精选
                startActivity(intent);
                break;
            case 46:
                intent.setClass(getActivity(), SelectedAlbumActivity.class);//精选专辑收录
                startActivity(intent);
                break;
            case 44:
                intent.setClass(getActivity(), MustBeChasedActivity.class);//每日漫画推荐
                startActivity(intent);
                break;
            case 50:
                intent.setClass(getActivity(), MustBeChasedActivity.class);//国漫
                startActivity(intent);
                break;
            case 35:
                intent.setClass(getActivity(), MustBeChasedActivity.class);//少女爱情
                startActivity(intent);
                break;
            case 33:
                intent.setClass(getActivity(), MustBeChasedActivity.class);//少年热血
                startActivity(intent);
                break;
            case 37:
                intent.setClass(getActivity(), MustBeChasedActivity.class);//国漫
                startActivity(intent);
                break;
        }
    }

    @Override
    public void pictureItemClick(PictureNewItem.WelfaresEntity pnwe,
                                 int itemPosition, List<String> imgUrl, ImageView imageView) {
    }

    @Override
    public void searcherItemClick(SearchIconItem.ThemesEntity stid) {
    }

    @Override
    public void homeItemClick(HomePageItem.ListsEntity.ThemeListEntity hlt) {
        String url = hlt.getUrl();
        Intent intent = new Intent();
        intent.putExtra("url",url);
        intent.putExtra("title",hlt.getName());
        intent.setClass(getActivity(), WebViewActivity.class);
        startActivity(intent);
    }


    @Override
    public void onRefresh() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        handler.sendEmptyMessageDelayed(0, 3000);

    }
}




















